package com.ysy.logistics.service.supplier.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ysy.common.entities.BaseEntity;
import com.ysy.logistics.entities.supplier.SupGoods;
import com.ysy.logistics.entities.supplier.Supplier;
import com.ysy.logistics.entities.supplier.dto.SupplierDto;
import com.ysy.logistics.entities.supplier.vo.SupplierQueryVO;
import com.ysy.logistics.mapper.supplier.SupGoodsMapper;
import com.ysy.logistics.mapper.supplier.SupplierMapper;
import com.ysy.logistics.service.supplier.SupplierService;
import com.ysy.logistics.util.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @ClassDescription:
 * @Author:姚斯羽
 * @Create:2025/3/25 14:24
 **/
@Service
public class SupplierServiceImpl extends ServiceImpl<SupplierMapper, Supplier> implements SupplierService {

    @Resource
    private SupplierMapper supplierMapper;
    @Resource
    private SupGoodsMapper supGoodsMapper;

    @Override
    public Page<SupplierDto> listByPage(PageInfo<SupplierQueryVO> pageInfo) {
        //查询出供应商列表
        Page<SupplierDto> page = supplierMapper.listByPage(pageInfo.getPage(), pageInfo.getCriteria());

        //查询出供应商对应的商品
        SupplierQueryVO criteria = Optional.ofNullable(pageInfo.getCriteria()).orElse(new SupplierQueryVO());
        if (!CollectionUtils.isEmpty(page.getRecords())) {
            List<SupplierDto> collect = page.getRecords().stream().map(supplierDto -> {
                LambdaQueryWrapper<SupGoods> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(SupGoods::getSupId, supplierDto.getId());
                //如果有商品条件，则查询出对应的商品
                if (!criteria.supGoodsConditionEmpty()) {
                    queryWrapper.eq(SupGoods::getName, criteria.getGoodsName());
                }
                //预览只查询前三条
                queryWrapper.orderByAsc(SupGoods::getNum);
                queryWrapper.last("limit 3");
                supplierDto.setSupGoods(supGoodsMapper.selectList(queryWrapper));
                return supplierDto;
            }).collect(Collectors.toList());
            page.setRecords(collect);
        }


        return page;
    }
}
